<?php
namespace App\Http\Controllers\Message;

use App\Http\Components\JpushComponent;
use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

use App\library\UtilFunction;

/*
* 系统推送消息
*/
class SystemPushController extends MessageController{

    public function __construct(){
         parent::__construct();
    }
    
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            return $this->system_push($request);
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 推送
     * type=1 单人推送 =2群发
     * user_id为指定用户ID
     * message 推送标题
     * desc 推送描述
     * link 推送链接
     */
    public function system_push(Request $request){

        $type = $request->input('type');
        $is_to_all = false;
        if($type == 1){ //单人推送
            $user_id = $request->input('user_id');
            $userid_list[] = $user_id;
        }elseif($type == 2){//群发
            $user_list = $request->input('user_list');
            if(!empty($user_list)){ //指定发送多个人
                $user_list = explode(',', $user_list);
                $userid_list =array();
                foreach($user_list AS $pitem){
                    $user = UserModel::where('phone',$pitem)->orwhere('user_id',$pitem)->first();
                    if($user){
                        $user = $user->toArray();
                        if(!empty($user)){
                            $userid_list[] = $user['user_id'];
                        }
                    }
                }
            }else{  //群发所有人
               $is_to_all = true;
               $userid_list = array();
            }
        }else{
            return $this->json('0','数据类型有误');
        }

        $message = $request->input('message');
        $desc = $request->input('desc');
        $link = $request->input('link');
        $link_type = $request->input('link_type');
        $order_id = $request->input('order_id');
        $l_id = $request->input('l_id');


        if(!empty($userid_list) || $is_to_all){
            $publish = JpushComponent::push($is_to_all,$userid_list,$message,$desc,$link,$link_type,$order_id,$l_id);

            return $this->json('1','');
        }else{
            return $this->json('0','数据为空');
        }

    }
}
